﻿/**
 *ajax通讯，
 author:jiangxiangwei
 code:UTF-8
 *调用示例：
 var json={
 url:"select.do",  //请求地址
 method:"post",    //请求方式post get
 async:"true",     //true 异步  false 同步
 showMsg:true,   //是否要进度提示
 form:"form1",     //需提交的表单id
 params:{          //form表单外需提交的参数
 "name":"11",      //参数名 : 值
 "SQLID":"selectModule",
 },
 callback:[callFun1,callFun2]  //回调函数
 }
 new Ajax().sendData(json);
 */
function Ajax() {
    var XMLHttpReq;
    this.sendData = sendData;

    //创建  XMLHttpRequest请求
    function createHttpRequest() {
        if (window.XMLHttpRequest) {
            XMLHttpReq = new XMLHttpRequest();
        } else {
            if (window.ActiveXObject) { //
                try {
                    XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch (e) {
                    try {
                        XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
                    }
                    catch (e) {
                    }
                }
            }
        }
    }
    //核心函数，发送请求
    function sendData(json) {
        var args = getArgs(json);
        if (args.showMsg)
            showLoadingMessage(args.msg);
        //显示蒙层
        createHttpRequest();
        var content = getParmValue(args.form, args.params);
        var url = "";
        if (args.method != null && args.method == "get" || args.method == "GET") {
            url = args.url + "?" + content;
        } else {
            url = args.url;
        }
        XMLHttpReq.open(args.method, url, args.async);
        XMLHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        XMLHttpReq.onreadystatechange = function() {
            if (XMLHttpReq.readyState == 4 && XMLHttpReq.status == 200) {
                var res = XMLHttpReq.responseText;
                var rtn = null;
                try {
                    rtn = eval("(" + res + ")");
                    //转为json对象
                } catch(exception) {
                    alert("返回结果不能实例化为json！");
                }
                //执行回调函数
                if (args.callback != null)
                    for (var i = 0; i < args.callback.length; i++)
                        args.callback[i](rtn);
                if (args.showMsg)
                    hideLoadingMessage();
                //取消蒙层
            }
        };
        XMLHttpReq.send(content);
    }

    //组装请求参数
    function getParmValue(form, params) {
        var str = "";
        //从指定form表单取值
        if (form) {
            str = getContent(document.getElementById(form));
        }
        //组装额外指定的参数
        if (params) {
            for (var key in params) {
                if (str.length > 0)
                    str += "&";
                str += key + "=" + params[key];
            }
        }
        return str;
    }

    //获取参数ajax对象参数
    function getArgs(json) {
        var async = true;
        if (json.async != null)
            async = json.async;
        var showMsg = true;
        if (json.showMsg != null)
            showMsg = json.showMsg;
        var o = {
            url:json.url,
            method:json.method ? json.method : "POST",
            async:async,
            showMsg:showMsg,
            msg :json.msg ? json.msg : "",
            form:json.form ? json.form : null,
            params:json.params ? json.params : null,
            callback:json.callback ? json.callback : []
        };
        return o;
    }
    //获取form表单数据
    function getContent(theform) {
        var els = theform.elements;
        var len = els.length;
        var queryString = "";
        this.addField = function (name, value) {
            if (queryString.length > 0) {
                queryString += "&";
            }
            queryString += name + "=" + value;
        };
        for (var i = 0; i < len; i++) {
            var el = els[i];
            if (!el.disabled) {
                switch (el.type) {
                    case "text":
                    case "password":
                    case "hidden":
                    case "textarea":
                        this.addField(el.name, el.value);
                        break;
                    case "select-one":
                        if (el.selectedIndex >= 0) {
                            this.addField(el.name, el.options[el.selectedIndex].value);
                        }
                        break;
                    case "select-multiple":
                        for (var j = 0; j < el.options.length; j++) {
                            if (el.options[j].selected) {
                                this.addField(el.name, el.options[j].value);
                            }
                        }
                        break;
                    case "checkbox":
                    case "radio":
                        if (el.checked) {
                            this.addField(el.name, el.value);
                        }
                        break;
                }
            }
        }
        return queryString.substring(0, queryString.length);
    }
    //显示蒙层
    function showLoadingMessage(msg) {
        //蒙层
        var div = document.getElementById("JXW__loading_div");
        if (div == null) {
            div = document.createElement("DIV");
            document.body.appendChild(div);
            div.id = "JXW__loading_div";
            div.style.position = "absolute";
            div.style.top = "0px";
            div.style.filter = "alpha(opacity=20)";
            div.style.background = "#777";
            div.style.zindex = "2";
            div.style.left = "0px";
        }

        div.style.width = "100%";
        div.style.height = "100%";
        div.style.display = "";
        //进度提示
        var divImg = document.getElementById("JXW__loading_div_IMG");
        if (divImg == null) {
            divImg = document.createElement("DIV");
            document.body.appendChild(divImg);
            divImg.id = "JXW__loading_div_IMG";
            divImg.style.position = "absolute";
            divImg.innerHTML = "<img src='../../include/images/ajax.gif'><br><center><font color='red'>" + msg + "</font></center>";
        }

        divImg.style.top = document.body.clientHeight / 3;
        divImg.style.left = document.body.clientWidth / 3;
        divImg.style.display = "";
    }
    //隐藏蒙层
    function hideLoadingMessage() {
        var div = document.getElementById("JXW__loading_div");
        if (div != null)
            div.style.display = "none";
        var divImg = document.getElementById("JXW__loading_div_IMG");
        if (divImg != null)
            divImg.style.display = "none";
    }
}
